//
//  Delay.swift
//  18.GCD延时调用
//
//  Created by 左忠飞 on 2021/10/8.
//

import Foundation

typealias Task = (_ cancel:Bool) -> Void

func delay(_ time:TimeInterval,task:@escaping ()->()) -> Task?{
    
    func dispatch_later(block:@escaping ()->()){
        let t = DispatchTime.now() + time
        DispatchQueue.main.asyncAfter(deadline: t, execute: block)
    }
    
    var closure:(()->Void)? = task
    var result:Task?
    
    let delayedClosure:Task = { cancel in
        if let internalClosure = closure {
            if cancel == false {
                DispatchQueue.main.async {
                    internalClosure()
                }
            }
        }
        closure = nil
        result = nil
    }
    
    result = delayedClosure
    
    dispatch_later {
        if let delayedClosure = result {
            delayedClosure(false)
        }
    }
    
    return result;
    
}

func cancel(_ task:Task?){
    task?(true)
}
